package com.lagou.rpc.consumer.controller;

import com.lagou.rpc.api.IUserService;
import com.lagou.rpc.consumer.proxy.RpcClientProxy;
import com.lagou.rpc.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ConsumerController {

    @Autowired
    private RpcClientProxy rpcClientProxy;

    @RequestMapping("/getUser/{id}")
    public User getUser(@PathVariable("id") int id) {

        IUserService userService = getUserService();
        User user = userService.getById(id);
        if (user != null) {
            return user;
        } else {
            User userFault = new User();
            userFault.setId(0);
            userFault.setName("NOT EXISTS");
            return userFault;
        }
    }

    private IUserService getUserService() {
        Object proxy = rpcClientProxy.createProxy(IUserService.class);
        return (IUserService) proxy;
    }

    @RequestMapping("/addUser")
    public User addUser() {
        IUserService userService = getUserService();
        User user = userService.addUser();
        return user;
    }
}
